0%

摘抄map的排序

2020年4月27日 下午6:45

C++(十三)— map的排序 - 深度机器学习 - 博客园

对有序map中的key排序

  • map这里指定less作为其默认比较函数(对象),就是默认按键值升序排列
  • 可以自定义,按照键值升序排列,注意加载
  • 按照自定义内容进行排序,比如字符串的长度
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    #include<iostream>
    #include<algorithm>
    #include<stdio.h>
    #include <vector>
    #include<string>
    #include<map>
    #include <functional> // std::greater
    using namespace std;


    struct CmpByKeyLength {
    bool operator()(const string& k1, const string& k2)const {
    return k1.length() < k2.length();
    }
    };

    int main()
    {
    //1、map这里指定less作为其默认比较函数(对象),就是默认按键值升序排列
    // map<string, int> name_score_map;

    // 2、可以自定义,按照键值升序排列,注意加载
    // #include <functional> // std::greater
    // map<string, int, greater<string>> name_score_map;

    //3、按照自定义内容进行排序,比如字符串的长度
    map<string, int, CmpByKeyLength> name_score_map;

    name_score_map["LiMin"] = 90;
    name_score_map["ZiLinMi"] = 79;
    name_score_map["BoB"] = 92;
    name_score_map.insert(make_pair("Bing", 99));
    name_score_map.insert(make_pair("Albert", 86));

    map<string, int>::iterator iter;
    for ( iter = name_score_map.begin();iter != name_score_map.end();++iter) {
    cout << (*iter).first << endl;
    }

    system("pause");
    return 0;
    }

对有序map中的value排序

  • 把map中的元素放到序列容器(如vector)中,再用sort进行排序。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    #include<iostream>
    #include<algorithm>
    #include<stdio.h>
    #include <vector>
    #include<string>
    #include<map>
    #include <functional> // std::greater
    using namespace std;


    bool cmp(const pair<string, int>& a, const pair<string, int>& b) {
    return a.second < b.second;
    }

    int main()
    {
    //1、map这里指定less作为其默认比较函数(对象),就是默认按键值升序排列
    map<string, int> name_score_map;
    name_score_map["LiMin"] = 90;
    name_score_map["ZiLinMi"] = 79;
    name_score_map["BoB"] = 92;
    name_score_map.insert(make_pair("Bing", 99));
    name_score_map.insert(make_pair("Albert", 86));

    //输出添加的内容
    map<string, int>::iterator iter;
    for (iter = name_score_map.begin(); iter != name_score_map.end(); ++iter) {
    cout << (*iter).first << endl;
    }
    cout << endl;

    // 将map中的内容转存到vector中
    vector<pair<string, int>> vec(name_score_map.begin(), name_score_map.end());
    //对线性的vector进行排序
    sort(vec.begin(), vec.end(), cmp);
    for (int i = 0; i < vec.size(); ++i)
    cout << vec[i].first << endl;

    system("pause");
    return 0;
    }